package cn.edu.lingnan.service.impl;

import cn.edu.lingnan.context.BaseContext;
import cn.edu.lingnan.mapper.PaperMapper;
import cn.edu.lingnan.mapper.QuestionsMapper;
import cn.edu.lingnan.mongodb.SearchHistory;
import cn.edu.lingnan.service.ExamService;
import cn.edu.lingnan.service.PaperService;
import cn.edu.lingnan.user.dtos.AddPaperQuestionDto;
import cn.edu.lingnan.user.dtos.ListPaperDto;
import cn.edu.lingnan.user.dtos.ListQuestionDto;
import cn.edu.lingnan.user.pojos.*;
import cn.edu.lingnan.user.vos.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
 import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

import java.util.List;

@Service
@Slf4j
public class PaperServiceImpl implements PaperService {
    @Autowired
    private PaperMapper paperMapper;
    @Autowired
    private QuestionsMapper questionsMapper;

    @Autowired
    private ExamService examService;


    @Override
    public PageBean<?> list(ListPaperDto listPaperDto) {
        PageHelper.startPage(listPaperDto.getPage(), listPaperDto.getSize());

        // 标准化 orderType 为大写，并验证其有效性
        if (listPaperDto.getOrderType() == null) {
            listPaperDto.setOrderType("ASC"); // 默认排序方式
        } else {
            String orderTypeUpper = listPaperDto.getOrderType().toUpperCase();
            if ("ASC".equals(orderTypeUpper) || "DESC".equals(orderTypeUpper)) {
                listPaperDto.setOrderType(orderTypeUpper);
            } else {
                listPaperDto.setOrderType("ASC"); // 无效值时设置为默认
            }
        }

        Page<Paper> page = paperMapper.list(listPaperDto);
        return new PageBean<>(page.getTotal(), page.getResult());
    }


    @Override
    public void addPaper(Paper paper) {
        paperMapper.addPaper(paper);
    }

    @Override
    @Transactional
    public Integer deletePaper(Integer paperId) {
        //是否关联考试
        Integer count = examService.getExamIdByPaperId(paperId);
        if (count > 0) {
           return -1;
        }
        //先删除试卷试题关联表
        paperMapper.deletePaperQuestion(paperId);
        //再删除试卷
        paperMapper.deletePaper(paperId);
        return 1;
    }

    @Override
    public Paper getPaperById(Integer paperId) {
        return  paperMapper.getPaperById(paperId);
    }

    @Override
    public void updatePaper(Paper paper) {
        paperMapper.updatePaper(paper);
    }

    @Override
    public PaperWithQuestionVo getPaperWithQuestionVo(Integer paperId) {
        return paperMapper.getPaperWithQuestionVo(paperId);
    }


  @Autowired
  private MongoTemplate mongoTemplate;
    @Override
    public PageBean<Question> getQuestionList(ListQuestionDto listQuestionDto) {
        PageHelper.startPage(listQuestionDto.getPage(), listQuestionDto.getSize());
        Page<Question> page = questionsMapper.getQuestionList(listQuestionDto);
        Integer userId = BaseContext.getCurrentId();

        if(listQuestionDto.getQuestionName()!=null&& !listQuestionDto.getQuestionName().trim().isEmpty()){
            //保存搜索记录到Mogondb
             log.info("用户ID：{}，搜索内容：{}", userId, listQuestionDto.getQuestionName());
            saveSearchRecord(userId, listQuestionDto.getQuestionName());

        }
        return new PageBean<>(page.getTotal(), page.getResult());

    }

    /**
     * 保存搜索记录
     * @param userId
     * @param questionName
     */
    private void saveSearchRecord(Integer userId, String questionName) {
        Query query = new Query(Criteria.where("userId").is(userId));
        long count = mongoTemplate.count(query, SearchHistory.class);

        if (count >= 10) {
            // 查询最早的一条记录并删除
            query.limit(1).with(Sort.by(Sort.Direction.ASC, "searchTime"));
            SearchHistory oldestRecord = mongoTemplate.findOne(query, SearchHistory.class);
            if (oldestRecord != null) {
                mongoTemplate.remove(oldestRecord);
            }
        }


        // 插入新搜索记录
        SearchHistory newRecord = new SearchHistory();
        newRecord.setUserId(userId);
        newRecord.setQuestionName(questionName);
        newRecord.setSearchTime(LocalDateTime.now());

        mongoTemplate.save(newRecord);
    }


    /**
     * 获取最近搜索的搜索记录
     * @return
     */
    @Override
    public List<SearchHistory> getRecentSearches() {
    Query query = new Query(Criteria.where("userId").is(BaseContext.getCurrentId()))
                .limit(10)
                .with(Sort.by(Sort.Direction.DESC, "searchTime"));
        List<SearchHistory> historyList = mongoTemplate.find(query, SearchHistory.class);
        for (SearchHistory history : historyList) {
            history.setUserId(null);
        }
        return historyList;
    }

    @Override
    public void deleteSearchHistory(String id) {
        // 删除搜索记录
        mongoTemplate.remove(Query.query(Criteria.where("id").is(id)), SearchHistory.class);
    }


    @Override
    public  List<StoreVo> getQuestionBankList(Integer userId) {
        return  paperMapper.getQuestionBankList(userId);
    }

    @Override
    public Boolean deletePaperQuestion(Integer paperId, Integer questionId,Integer examId) {
        //考试中不能删除试题
        if(examId!=null){
            Integer status = examService.getExamStatus(examId);
            if (status !=0){
                return false;
            }
        }

//        Integer i = questionsMapper.countQuestionsId(questionId);
//        if (i > 0) {
//            return false;
//        }
        //查询该试卷是否关联考试
        Integer count = examService.getExamIdByPaperId(paperId);
        if (count > 0) {
            return false;
        }
        paperMapper.deletePaperQuestionById(paperId, questionId);
        return true;
    }




    @Override
    public void addPaperQuestion(AddPaperQuestionDto addPaperQuestionDto) {
        Integer paperId = addPaperQuestionDto.getPaperId();
        List<Integer> questionIds = addPaperQuestionDto.getQuestionIds();

        if (paperId == null || questionIds == null || questionIds.isEmpty()) {
            throw new IllegalArgumentException("参数错误：paperId 或 questionIds 为空！");
        }

        // 1. 查询已存在的题目ID
        List<Integer> existIds = paperMapper.findExistQuestionIds(paperId, questionIds);

        // 2. 找出还未关联的题目ID
        List<Integer> notExistIds = questionIds.stream()
                .filter(qid -> !existIds.contains(qid))
                .toList();  // 如果是 Java 8，可以用 .collect(Collectors.toList())

        // 3. 如果有需要插入的新题目，批量插入
        if (!notExistIds.isEmpty()) {
            paperMapper.batchInsertPaperQuestion(paperId, notExistIds);
        }

        // 4. 如果有已存在的题目，则抛出异常或拼接提示信息
        if (!existIds.isEmpty()) {
            // 做法1：直接抛出自定义异常，前端拿到后做提示
            // throw new CustomException("部分题目已存在，插入失败，已存在题目ID：" + existIds);

            // 做法2：仅仅提示日志，也可在返回值中带上已存在列表
            // 这里演示“抛出异常”，由 Controller 捕获或者全局异常处理捕获
            throw new RuntimeException("以下题目已存在，无法重复插入：" + existIds);
        }
    }

}
